 <?php

/**
 * Description of stdLoginStrategy
 *
 * @author ������
 */
class VKLoginStrategy extends LoginStrategy {

    public function doLogin(User $user, $auth_data) {
        $registry = Registry::getInstance();
        $registry->load->library('vkapi');
        //� ����� �� ������� ������ �� vk
        if (!isset($_COOKIE[$user->cookies_name_array['vk']])) {
            return false;
        }
        $vk_cookie = $_COOKIE[$user->cookies_name_array['vk']];
        if (empty($vk_cookie)) {
            return false;
        }
        $cookie_data = array();
        foreach (explode('&', $vk_cookie) as $item) {
            $item_data = explode('=', $item);
            $cookie_data[$item_data[0]] = $item_data[1];
        }
        // ��������� sig
        $string = sprintf("expire=%smid=%ssecret=%ssid=%s%s", $cookie_data['expire'], $cookie_data['mid'], $cookie_data['secret'], $cookie_data['sid'], VK_APP_PASSWORD);

        if (md5($string) == $cookie_data['sig']) {

            $VK = new vkapi(VK_APP_ID, VK_APP_PASSWORD);
            $resp = $VK->api('getProfiles', array('uids' => $cookie_data['mid'],
                'fields' => 'firstname, lastname, phone, has_mobile,photo, photo_medium, photo_big,  birthdate'));

            $data = array();
            if (!$user->LRModel->hasUserInBase($cookie_data['mid'])) {
                $password = md5($this::generateCode(10));
                $user_id = LRmodel::adduser($cookie_data['mid'], $password);

                LRmodel::updateProfile(array('realname' => $resp['response'][0]['first_name'] . ' ' . $resp['response'][0]['last_name'],
                    'phone' => null,
                    'mail' => null,
                    'bday' => $resp['response'][0]['bdate'],
                    'photo_small' => $resp['response'][0]['photo'],
                    'photo_medium' => $resp['response'][0]['photo_medium'],
                    'photo_big' => $resp['response'][0]['photo_big']), $user_id);
                $user->fireEvent('message', array('message' => "Новый пользователь " . $cookie_data['mid'] . " добавлен в базу!"));
            }
            $data = $user->LRModel->getUserDataByLogin($cookie_data['mid']);
            $this->_makeLogin($user, $data);
            $user->fireEvent("message", array('message' => 'Вход успешен!'));
            //$resp - ������ � ������ �� �������� 
            setcookie($user->cookies_name_array['vk'], "", 0, "/", "." . $_SERVER['HTTP_HOST']);
            return true;
        }
    }

}

?>
